package me.xiaoyan.android.net;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;

import me.xiaoyan.android.net.HttpManager;
import me.xiaoyan.android.net.HttpManager.HTTPMETHOD;
import me.xiaoyan.android.widget.AppSetting;
import me.xiaoyan.android.widget.YLog;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

/**
 * 应用更新类 ,使用方法:<br>
 * 
 * <pre>
 * AppUpdate appUpdate = new AppUpdate(getApplicationContext());
 * AppUpdate.checkNewVersion(new Handler(){
 * 	public void handleMessage(Message msg) {
 * 		if(msg.what == AppUpdate.APPUPDATE_GETVERSION_SUCCESS && msg.arg1 == 1){
 * AppUpdate.upgradeApk();
 * 		}else{
 * Toast.makeText(getApplicationContext(), "您使用的软件为最新版本", Toast.LENGTH_LONG).show();
 * 		}
 * 	}
 * });
 * 
 * <pre>
 * @author xiaoyan
 * 
 */
public class AppUpdate {
	private static final String TAG = YLog.getTag(AppUpdate.class);
	/**
	 * 保存地址
	 */
	private static String NEWAPKSAVEPATH = "ttmm_update.apk";
	public static final int APPUPDATE_GETVERSION_SUCCESS = 1;

	/**
	 * 检查更新的服务器 地址
	 */
	public String mserverVersionUrl = AppSetting.CHECK_NEWVER_URL;

	private Context mcontext;
	/**
	 * 新软件的下载地址
	 */
	private String downloadUrl = AppSetting.NEWVER_FILENAME;

	public AppUpdate(Context context) {
		this.mcontext = context;
	}

	/**
	 * 判断是否 有新版本,在handler 处理消息时 请判断message的what
	 * 是否等于1或AppUpdate.APPUPDATE_GETVERSION_SUCCESS 然后 判断 message的arg1 <br>
	 * 1.为有新的软件版本 请调用AppUpdate.upgradeApk <br>
	 * 2.为当前软件为最新版本
	 * 
	 * @param handler
	 */
	public void checkNewVersion(final Handler handler) {
		final ProgressDialog pd = ProgressDialog.show(mcontext, "", "联网中...");
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					int localVersion = mcontext.getPackageManager()
							.getPackageInfo(mcontext.getPackageName(), 0).versionCode;
					Log.i(TAG, "mserverVersionUrl" + mserverVersionUrl);
					String source = new String(HttpManager.openUrl(
							mserverVersionUrl, HTTPMETHOD.GET, "").getContent());
					
					pd.dismiss();
					Log.i(TAG, "checkNewVersion" + source);

					JSONObject upo = new JSONObject(source);
					int serverVersion = upo.getInt("code_ver");
					Message msg = handler.obtainMessage();
					String ver = upo.getString("soft_ver");

					NEWAPKSAVEPATH = "ttmm_" + ver + ".apk";
					msg.what = APPUPDATE_GETVERSION_SUCCESS;
					msg.arg1 = serverVersion > localVersion ? 1 : 0;
					handler.sendMessage(msg);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}).start();
	}

	/**
	 * 升级软件
	 * 
	 * @param downloadUrl
	 * @param savePath
	 */
	public void upgradeApk() {
		final ProgressDialog pd = new ProgressDialog(mcontext);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setMessage("正在下载更新文件...");
		pd.show();
		new Thread() {
			@Override
			public void run() {
				try {
					YLog.d(TAG, downloadUrl);
					File f = getFileFromServer(downloadUrl, pd, NEWAPKSAVEPATH);
					installApk(f);
					pd.dismiss();
				} catch (Exception e) {
					pd.dismiss();
					Toast.makeText(mcontext, "下载更新文件失败,请重试!", Toast.LENGTH_LONG)
							.show();
					e.printStackTrace();
				}
			}
		}.start();
	}

	/**
	 * 安装更新文件
	 * 
	 * @param apkfile
	 */
	private void installApk(File apkfile) {
		if (apkfile.exists()) {
			Intent installIntent = new Intent(Intent.ACTION_VIEW);
			installIntent.setDataAndType(
					Uri.parse("file://" + apkfile.toString()),
					"application/vnd.android.package-archive");
			mcontext.startActivity(installIntent);
		}
	}

	private File getFileFromServer(String path, ProgressDialog pd,
			String savePath) throws IOException {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			// 获取到文件的大小
			pd.setMax(conn.getContentLength());
			InputStream is = conn.getInputStream();
			File file = new File(Environment.getExternalStorageDirectory(),
					savePath);
			if (file.exists()) {
				file.delete();
			}
			FileOutputStream fos = new FileOutputStream(file);
			BufferedInputStream bis = new BufferedInputStream(is);
			byte[] buffer = new byte[1024];
			int len;
			int total = 0;
			while ((len = bis.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
				total += len;
				// 获取设置当前下载量
				pd.setProgress(total);
			}
			fos.close();
			bis.close();
			is.close();
			return file;
		}
		return null;
	}
}
